import pandas as pd
from datetime import datetime
import tkinter as tk
from tkinter import filedialog
import os
import sys


def csv_to_asc(csv_path, asc_path):
    try:
        # 读取CSV文件
        df = pd.read_csv(csv_path, names=['Time', 'ID', 'Channel', 'Data'])

        # 写入ASC文件
        with open(asc_path, 'w') as f:
            # 写入头部信息
            current_time = datetime.now().strftime("%a %b %d %H:%M:%S %Y")
            f.write(f"date {current_time}\n")
            f.write("base hex  timestamps absolute\n")
            f.write("no internal events logged\n")
            f.write("// version 7.0.0\n")

            # 写入数据行
            for _, row in df.iterrows():
                timestamp = f"{row['Time']:.6f}"
                id_with_x = f"{row['ID']}x"
                data = row['Data'].strip()
                data_bytes = len(data.split())
                output_line = f"{timestamp} 1  {id_with_x:<14} Rx   d {data_bytes} {data}\n"
                f.write(output_line)
        return True
    except Exception as e:
        print(f"转换过程中出现错误: {str(e)}")
        return False


def select_file():
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    file_path = filedialog.askopenfilename(
        title="选择CSV文件",
        filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
    )
    return file_path


def main():
    csv_path = select_file()

    if not csv_path:
        print("没有选择文件！")
        input("按回车键退出...")
        return

    # 生成输出文件路径（与输入文件同目录，但扩展名改为.asc）
    asc_path = os.path.splitext(csv_path)[0] + '.asc'

    # 执行转换
    if csv_to_asc(csv_path, asc_path):
        print(f"转换完成！\n输出文件: {asc_path}")
    else:
        print("转换失败！")

    input("按回车键退出...")


if __name__ == "__main__":
    main()